import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { withRouter } from 'react-router';
import Table from '@knownsec/react-component/dist/Table';
import Button from '@kuiper-components/button';
import Pagination from '@knownsec/react-component/dist/Pagination';
import searchStringBuilder from '@kuiper-components/page-table';
import EmptyData from '../../../components/empty/EmptyData';
import {
	getParams,
	searchStringParams,
	turnToUrlparam,
} from '../../../helpers/getUrlParams';
import { datetime } from '../../../../common/formatter';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import s from './style.module.css';
import Toolbox from './Toolbox';
import fetchFer from 'API/fetch';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';

import confirm from '../../../components/confirm';
import { cloneDeep } from 'lodash';
import Message from '@knownsec/react-component/dist/Message';

const routePrefix = '/dashboard/downList';
function downFiles({ className, history, location }) {
	let set = null;
	const columns = [
		{
			title: '任务ID',
			key: 'download_task_id',
			dataIndex: 'download_task_id',
			render(e) {
				return (
					<Tooltip
						overlay={<div className={cn('')}>{e}</div>}
						placement={'topLeft'}
					>
						<span className={cn('ell')}>{e}</span>
					</Tooltip>
				);
			},
		},
		{
			title: '资产地址',
			key: 'asset',
			dataIndex: 'asset',
			render(e, row) {
				const all = row.all_assets;
				return (
					<Tooltip
						overlay={
							<div className={cn('')}>
								{all.map(x => (
									<p className={s.text} key={x}>
										{x}
									</p>
								))}
							</div>
						}
						placement={'topLeft'}
					>
						<span className={cn('ell')}>{e}</span>
					</Tooltip>
				);
			},
		},
		{
			title: '导出方式',
			key: 'download_type',
			dataIndex: 'download_type',
			width: 120,
			render(affects) {
				return affects || '- - -';
			},
		},
		{
			title: '任务下发时间',
			key: 'task_create_time',
			dataIndex: 'task_create_time',
			render: e => {
				return datetime(e) || '- -';
			},
		},
		{
			title: '生成时间',
			key: 'report_created_at',
			dataIndex: 'report_created_at',
			render: (e, row) => {
				const time = row.report_create_time;
				if (e) {
					if (time.start_date) {
						return (
							<Tooltip
								overlay={
									<div
										className={cn('')}
									>{`查询时间范围:${time.start_date}~${time.end_date}`}</div>
								}
								placement={'top'}
							>
								<span className={cn('ell')}>{datetime(e)}</span>
							</Tooltip>
						);
					} else {
						return <span className={cn('ell')}>{datetime(e)}</span>;
					}
				} else {
					return '- -';
				}
			},
		},
		{
			title: '状态',
			key: 'status_text',
			dataIndex: 'status_text',
			width: 120,
			render: (e, row) => {
				const statusCo = { error: '#e61214', success: '#11ab4e' };
				return (
					<span style={{ color: statusCo[row.status] }}>{e}</span> || '- -'
				);
			},
		},
		{
			title: '操作',
			width: 120,
			key: 'description',
			dataIndex: 'description',
			render(description, row) {
				return (
					<>
						{row.is_downloadable && row.process === '100%' && (
							<Button
								primary
								link
								className={cn(s.btn, s.mr16)}
								onClick={() => {
									downFun(row);
								}}
							>
								下载
							</Button>
						)}
						{!row.is_downloadable && row.process === '100%' && (
							<Tooltip
								overlay={<div>已过期，存储期限一周</div>}
								placement={'top'}
							>
								<span className={cn('ell', s.disabled)}>下载</span>
							</Tooltip>
						)}
						<Button
							primary
							link
							className={cn(s.btn)}
							onClick={() => {
								handleDelete([row.key]);
							}}
						>
							删除
						</Button>
					</>
				);
			},
		},
	];
	const params = getParams();
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const [filter, setFilter] = React.useState(
		params || {
			asset: '',
			status: '',
			page: 1,
			limit: 10,
		}
	);
	const [loading, setLoading] = React.useState(true);
	const [tableData, setTableData] = React.useState([]);
	const [count, setCount] = React.useState(0);
	const [type, setType] = React.useState('empty');
	const getData = async () => {
		const params_ = turnToUrlparam(filter);
		const res = await fetchFer(`api/v2/report/export_list?${params_}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			console.log('[  ]-69', err);
			return {};
		});
		if (res.msg === 'ok') {
			if (!res.result[0] && filter.page > 1) {
				pageChange(filter.page - 1, filter.limit);
				return false;
			}
			res.result.forEach((e, i) => {
				e.key = e.download_task_id;
			});
			setTableData(res.result);
			setCount(res.total_count);
		}
		setLoading(false);
	};

	const pageChange = (page, limit) => {
		const search = searchStringParams({
			...filter,
			page,
			limit,
		});
		const obj = cloneDeep(filter);
		obj.page = page;
		obj.limit = limit;
		setLoading(true);
		setFilter(obj);
		history.replace(`${routePrefix}?${search}`);
	};
	const handleFilterChange = val => {
		const search = searchStringBuilder(location.search, {
			...val,
			page: 1,
			limit: 10,
		});
		setLoading(true);
		setFilter({ ...filter, ...val, page: 1, limit: 10 });
		history.replace(`${routePrefix}?${search}`);
	};
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const downFun = row => {
		const { key, asset, file_type } = row;
		fetch(`/api/v2/report/download_completed?download_task_id=${key}`)
			.then(res => {
				if (res.ok) {
					return res.blob();
				}
			})
			.then(blob => {
				const body = document.querySelector('body');
				const url = window.URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.download = `[${asset}]ScanV安全监测报告.` + file_type;
				a.href = url;
				setTimeout(function () {
					body.appendChild(a);
					a.click();
					body.removeChild(a);
					window.URL.revokeObjectURL(a.href);
				}, 500);
			})
			.catch(error => {
				return {};
			});
	};
	const handleDelete = id => {
		const ids = id || selectedRowKeys;
		confirm.warning({
			message: `您确认删除所选任务？`,
			okText: '删除',
			cancelText: '取消',
			title: '',
			onCancel: () => {
				setSelectedRowKeys([]);
			},
			onOk: async () => {
				const res = await fetchFer(`api/v2/report/delete`, {
					method: 'POST',
					body: JSON.stringify({ download_task_ids: ids.join(',') }),
				});
				if (res.code === 200) {
					Message.show({
						type: 'success',
						placement: 'top',
						message: `删除成功`,
					});
					getData();
				} else {
					Message.show({
						type: 'error',
						message: '删除失败',
						placement: 'top',
					});
				}
				setSelectedRowKeys([]);
			},
		});
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};
	React.useEffect(() => {
		if (!loading) setType('img');
	}, [loading]);
	React.useEffect(() => {
		getData();
		clearInterval(set);
		set = setInterval(() => {
			getData();
		}, 10 * 1000);
		return () => {
			clearInterval(set);
		};
	}, [filter]);
	return (
		<div className={cn(className, s.operationLog)}>
			<Breadcrumb>
				<Item key="dashboard" disabled>
					报表中心
				</Item>
				<Item key="downList" active>
					报告下载
				</Item>
			</Breadcrumb>
			<div className={cn(className, s.operationLog)}>
				<div className={s.content}>
					<Toolbox reSearch={handleFilterChange} value={filter} />
					<div className={s.tableContainer}>
						<Table
							className={s.smallTable}
							rowSelection={rowSelection}
							columns={columns}
							data={tableData}
							pro
							loading={loading}
							empty={<EmptyData type={type} className={s.nobor} />}
							key={Date.now()}
						/>
						<div className={cn(s.df, 'jcsb aic mt5')}>
							<Button
								link
								className={cn(s.batchRemove, 'p0 m0')}
								disabled={!selectedRowKeys.length}
								onClick={() => {
									handleDelete();
								}}
							>
								批量删除
							</Button>
							{count > 10 && (
								<div className={cn(s.df, 'jcfe')}>
									<Pagination
										current={filter.page || 1}
										pageSize={filter.limit || 10}
										showQuickJumper={{ goButton: true }}
										showSizeChanger={true}
										pageSizeOptions={['10', '20', '50']}
										total={count}
										showTotal={total => `共${total}条`}
										onChange={pageChange}
									/>
								</div>
							)}
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}

downFiles.propTypes = {
	className: PropTypes.string,
	history: PropTypes.objectOf(
		PropTypes.shape({
			push: PropTypes.func.isRequired,
		})
	),
	location: PropTypes.objectOf(
		PropTypes.shape({
			search: PropTypes.object,
		})
	),
};
downFiles.defaultProps = {
	className: '',
};

export default withRouter(downFiles);
